from ..database import database, TABLE_PREFIX
from peewee import *


class TableSeq(database.Model):
    code = CharField(primary_key=True, max_length=40)
    seq = IntegerField(default=0)

    # class Meta:
    #     db_table = '{}_table_seqs'.format(TABLE_PREFIX)

    @classmethod
    def get_seq(cls, code):
        import random
        with database.database.transaction() as  txn:
            seq, created = TableSeq.get_or_create(code=code,
                                                  defaults={
                                                      'code': code,
                                                      'seq': random.randint(10000, 999999)
                                                  })
            next_id = seq.seq + 1
            TableSeq.update(seq=next_id).where(TableSeq.code == code).execute()

            txn.commit()
            return next_id

#
# @pre_save(sender=Model_)
# def global_id_key(model_class, instance, created):
#     if not created: return
#     import random
#     if hasattr(model_class, '_meta'):
#         _meta = getattr(model_class, '_meta')
#         db_table = None
#         if hasattr(_meta, 'db_table'):
#             db_table = getattr(_meta, 'db_table')
#         if db_table:
#             id_field = _meta.fields.get('id', None)
#
#             if id_field:
#                 if isinstance(id_field, PrimaryKeyField) or id_field.primary_key:
#                     next_id = None
#                     with database.database.transaction() as txn:
#                         next_table_key, created = TableSeq.get_or_create(code=db_table,
#                                                                          defaults={'code': db_table,
#                                                                                    'seq': random.randint(10000,
#                                                                                                          999999)})
#
#                         next_id = next_table_key.next_id + 1
#                         TableSeq.update(next_id=next_id).where(TableSeq.code == db_table).execute()
#                         txn.commit()
#                     if next_id:
#                         setattr(instance, 'id', str(next_id).zfill(24))
